package com.okilo.online.app.apt

import android.annotation.SuppressLint
import android.text.Editable
import android.text.InputType
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.okilo.online.app.R
import com.okilo.online.app.event.OkiloEventPointType
import com.okilo.online.app.request.HttpHelper
import com.okilo.online.app.tools.apt.OkiloRecyclerViewAdapter
import com.okilo.online.app.tools.apt.OkiloViewHolderHelper
import com.okilo.online.app.tools.decoration.GridSpacingItemDecoration
import com.okilo.online.app.tools.shared.OkiloSharedHp
import com.okilo.online.app.tools.shared.OkiloSharedKey
import com.okilo.online.app.weight.font.OkiloRbtMediumEditText
import org.json.JSONObject

/**
 * OkiloLoan
 * @Author wwdeng
 * @CreateTime: 2024/11/19 13:54
 * @Annotation：认证流程步骤适配器
 */
class OkiloStepGeneralApt(recyclerView: RecyclerView?): OkiloRecyclerViewAdapter<JSONObject>(recyclerView) {
    override fun getItemViewType(position: Int): Int {
        val model = getItem(position)
        when(model.optString("action")){
            "GENDER_PICK" -> {//性别
                return R.layout.okilo_fmt_step_general_gender_item
            }
            "CONTACT_GROUP_RELATION" -> {//联系人关系
                return R.layout.okilo_fmt_step_contact_relation_item
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                return R.layout.okilo_fmt_step_contact_mobile_item
            }
            "DATE_PICK",
            "SELECT",
            "PICK_AREA",
            "PICK_STATE",
            "PICK_CITY" -> {//出生日期选择,选择,选择城市
                return R.layout.okilo_fmt_step_general_select_item
            }
            else -> {//输入框
                return R.layout.okilo_fmt_step_general_input_item
            }
        }
    }

    override fun setItemChildListener(helper: OkiloViewHolderHelper, viewType: Int) {
        helper.setItemChildClickListener(R.id.okiloProcessStepSelectItemLayout)//选择
        helper.setItemChildClickListener(R.id.okiloProcessStepContactSelectImage)//选择联系人
        helper.setItemChildClickListener(R.id.okiloProcessStepContactMobileText)
    }

    override fun fillData(helper: OkiloViewHolderHelper, position: Int, model: JSONObject) {
        //名称
        val okiloProcessStepItemTitle = helper.getTextView(R.id.okiloProcessStepItemTitle)
        val showTitle = model.optString("title")
        okiloProcessStepItemTitle.text = findKeywordColor(getColor(R.color.okilo_color_ffff4d3e),showTitle,"*")

        when(model.optString("action")){
            "DATE_PICK",
            "SELECT",
            "PICK_AREA",
            "PICK_STATE",
            "PICK_CITY" -> {//出生日期选择,选择,选择城市
                showAuthStepSelectItemView(helper,position,model)
            }
            "CONTACT_GROUP_RELATION" -> {//联系人关系
                showAuthStepContactRelationItemView(helper,position,model)
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                showAuthStepContactMobileItemView(helper,position,model)
            }
            "GENDER_PICK" -> {//性别
                showAuthStepGenderItemView(helper,position,model)
            }
            else -> {//输入框
                showAuthStepInputItemView(helper,position,model)
            }
        }
    }

    /**
     * 输入框类型
     */
    private fun showAuthStepInputItemView(helper: OkiloViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val okiloProcessStepInput = helper.getView<OkiloRbtMediumEditText>(R.id.okiloProcessStepInput)
        okiloProcessStepInput.hint = model.optString("hint")
        when(model.optString("paramName")){
            "monthlyIncome" -> {//月收入，只能输入数字
                okiloProcessStepInput.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
            }
            else -> {
                okiloProcessStepInput.inputType = InputType.TYPE_CLASS_TEXT
            }
        }

        var showText = ""
        val selectItem = model.optJSONObject("selectItem")
        if (selectItem != null) {
            showText = selectItem.optString("title")
        }
        okiloProcessStepInput.setText(showText)
        okiloProcessStepInput.setInputFocusChangeListener(object : OkiloRbtMediumEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
//                if (hasFocus){
//                    authStepEdit.shapeDrawableBuilder
//                        .setStrokeColor(getColor(R.color.color_ff0569ff))
//                        .intoBackground()
//                } else {
//                    authStepEdit.shapeDrawableBuilder
//                        .setStrokeColor(getColor(R.color.color_ffeceff3))
//                        .intoBackground()
//                }
            }
            override fun onCompleteAction(v: View?, remark: String?) {
                var eventType = String.Companion.format(OkiloEventPointType.OKILO_FORM_TRACK.STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}")
                if (model.has("stepType") && model.optString("stepType") == "CONTACT"){
                    eventType = String.Companion.format(OkiloEventPointType.OKILO_FORM_TRACK.STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}_${model.optString("stepItemIndex")}")
                }
                HttpHelper.addPoint(eventType,remark)
            }
        })

        okiloProcessStepInput.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                okiloProcessStepInput.clearFocus()
                true
            }
            false
        }
        okiloProcessStepInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })
    }

    /**
     * 生日选择,选择
     */
    private fun showAuthStepSelectItemView(helper: OkiloViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val okiloProcessStepSelectText = helper.getTextView(R.id.okiloProcessStepSelectText)
        okiloProcessStepSelectText.hint = model.optString("hint")
        var showTitle = ""
        val selectItem = model.optJSONObject("selectItem")
        if (selectItem != null){
            showTitle = selectItem.optString("title")
        }
        okiloProcessStepSelectText.text = showTitle

        val okiloProcessStepSelectIcon = helper.getImageView(R.id.okiloProcessStepSelectIcon)
        okiloProcessStepSelectIcon.setImageResource(R.mipmap.okilo_down_black_icon)
    }

    /**
     * 性别选择
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun showAuthStepGenderItemView(helper: OkiloViewHolderHelper, position: Int, model: JSONObject){
        val okiloProcessStepGenderListView = helper.getView<RecyclerView>(R.id.okiloProcessStepGenderListView)
        val layoutManager = GridLayoutManager(mContext, 2)
        okiloProcessStepGenderListView.layoutManager = layoutManager
        if (okiloProcessStepGenderListView.itemDecorationCount == 0){
            val itemDecoration = GridSpacingItemDecoration.Companion.create(
                spanCount = 2,
                spacingDp = 13,
                context = mContext,
                includeEdge = false,
                includeTop = true,
                includeBottom = false,
                topSpacingType = GridSpacingItemDecoration.TopSpacingType.BETWEEN_ROWS_ONLY
            )
            okiloProcessStepGenderListView.addItemDecoration(itemDecoration)
        }
        val genderItemAdapter = OkiloStepGenderItemApt(okiloProcessStepGenderListView)
        okiloProcessStepGenderListView.adapter = genderItemAdapter
        okiloProcessStepGenderListView.itemAnimator = DefaultItemAnimator()
        genderItemAdapter.setOnItemChildClickListener{ _, childView, position ->
            val item = genderItemAdapter.getItem(position)
            if (item.optBoolean("isSelected",false)){
                return@setOnItemChildClickListener
            }
            genderItemAdapter.data.forEach {
                it.put("isSelected",false)
            }
            item.put("isSelected",true)
            model.put("selectItem",item)
            genderItemAdapter.notifyDataSetChanged()

            val subRemark = item.optString("value")
            HttpHelper.addPoint(String.Companion.format(OkiloEventPointType.OKILO_CLICK_TRACK.STEP_XX_SELECT,"${model.optString("stepTitle")}_${model.optString("paramName")}"),subRemark)
        }
        val childList = arrayListOf<JSONObject>()
        val dataArray = model.optJSONArray("values")
        if (dataArray != null) {
            for (i in 0..<dataArray.length()) {
                val genderItem = dataArray.optJSONObject(i)
                childList.add(genderItem)
            }
        }
        genderItemAdapter.data = childList
    }

    /**
     * 联系人关系
     */
    private fun showAuthStepContactRelationItemView(helper: OkiloViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val showHint = model.optString("hint")
        //选择关系
        val okiloProcessStepContactRelationSelect = helper.getTextView(R.id.okiloProcessStepContactRelationSelect)
        okiloProcessStepContactRelationSelect.hint = showHint
        //输入关系
        val okiloProcessStepContactRelationInput = helper.getView<OkiloRbtMediumEditText>(R.id.okiloProcessStepContactRelationInput)
        //todo 此处确实选择Other时输入框的提示
        okiloProcessStepContactRelationInput.hint = model.optString("relationOtherHint")
        okiloProcessStepContactRelationInput.visibility = View.GONE

        var showTitle = ""
        var showOtherValue = ""
        if (model.has("selectItem")){
            val selectItem = model.optJSONObject("selectItem")
            selectItem?.let {
                showTitle = selectItem.optString("title")
                if (showTitle == model.optString("relationOtherKey")){
                    okiloProcessStepContactRelationInput.visibility = View.VISIBLE
                    if (selectItem.has("otherValue")){
                        showOtherValue = selectItem.optString("otherValue","")
                    }
                }
            }
        }
        okiloProcessStepContactRelationSelect.text = showTitle

        //关系为“Other”时，输入框允许输入
        okiloProcessStepContactRelationInput.isEnabled = showTitle == model.optString("relationOtherKey")
        okiloProcessStepContactRelationInput.setText(showOtherValue)
        okiloProcessStepContactRelationInput.setInputFocusChangeListener(object : OkiloRbtMediumEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
//                if (hasFocus){
//                    authStepEdit.shapeDrawableBuilder
//                        .setStrokeColor(getColor(R.color.color_ff0569ff))
//                        .intoBackground()
//                } else {
//                    authStepEdit.shapeDrawableBuilder
//                        .setStrokeColor(getColor(R.color.color_ffeceff3))
//                        .intoBackground()
//                }
            }
            override fun onCompleteAction(v: View?, remark: String?) {
                var eventType = String.Companion.format(OkiloEventPointType.OKILO_FORM_TRACK.STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}")
                if (model.has("stepType") && model.optString("stepType") == "CONTACT"){
                    eventType = String.Companion.format(OkiloEventPointType.OKILO_FORM_TRACK.STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}_${model.optString("stepItemIndex")}")
                }
                HttpHelper.addPoint(eventType,remark)
            }
        })
        okiloProcessStepContactRelationInput.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                okiloProcessStepContactRelationInput.clearFocus()
                true
            }
            false
        }

        okiloProcessStepContactRelationInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                if (model.has("selectItem")){
                    val selectItem = model.optJSONObject("selectItem")
                    selectItem?.let {
                        selectItem.put("otherValue",s.toString())
                    }
                }
            }
        })
    }

    /**
     * 联系电话
     */
    private fun showAuthStepContactMobileItemView(helper: OkiloViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val showHint = model.optString("hint")
        val okiloProcessStepContactMobileText = helper.getTextView(R.id.okiloProcessStepContactMobileText)
        okiloProcessStepContactMobileText.hint = showHint
        val okiloProcessStepContactMobileInput = helper.getView<OkiloRbtMediumEditText>(R.id.okiloProcessStepContactMobileInput)
        okiloProcessStepContactMobileInput.hint = showHint
        if (model.has("selectItem")){
            val showValue = model.getJSONObject("selectItem").optString("title")
            okiloProcessStepContactMobileText.text = showValue
            okiloProcessStepContactMobileInput.setText(showValue)
        }
        okiloProcessStepContactMobileInput.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                okiloProcessStepContactMobileInput.clearFocus()
                true
            }
            false
        }
        okiloProcessStepContactMobileInput.setInputFocusChangeListener(object : OkiloRbtMediumEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
            }
            override fun onCompleteAction(v: View?, remark: String?) {
                val eventType = String.Companion.format(OkiloEventPointType.OKILO_FORM_TRACK.STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}_${model.optString("stepItemIndex")}")
                HttpHelper.addPoint(eventType,remark)
            }
        })
        okiloProcessStepContactMobileInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })

        //是否支持通讯录选择
        if (model.optBoolean("isContactPick")){
            helper.setVisibility(R.id.okiloProcessStepContactSelectImage, View.VISIBLE)
            //是否是审核账号
            val isAdmin = OkiloSharedHp.gOkiloSharedBoolean(OkiloSharedKey.SP_OKILO_IS_CONFIG_ACCOUNT)
            if(isAdmin){//审核账号 - 允许输入或选择
                okiloProcessStepContactMobileText.visibility = View.GONE
                okiloProcessStepContactMobileInput.visibility = View.VISIBLE
            } else {//非审核账号，只能选择
                okiloProcessStepContactMobileText.visibility = View.VISIBLE
                okiloProcessStepContactMobileInput.visibility = View.GONE
            }
        } else {
            helper.setVisibility(R.id.okiloProcessStepContactSelectImage, View.INVISIBLE)
            okiloProcessStepContactMobileText.visibility = View.GONE
            okiloProcessStepContactMobileInput.visibility = View.VISIBLE
        }
    }

    private fun findKeywordColor(color: Int, text: String, key: String): SpannableString {
        val spString = SpannableString(text)
        if (!text.contains(key)){
            return spString
        }
        val start = text.indexOf(key)
        val end = start + key.length
        spString.setSpan(ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spString
    }
}